package com.imay.live.view.custom;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.imay.live.adapter.ChooseTagAdapter;
import com.imay.live.manager.SensitiveWordFilterManager;
import com.imay.live.utils.AnimationUtil;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.NoUnderlineClickableSpan;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.live.R;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import cn.dreamtobe.kpswitch.util.KeyboardUtil;
import me.kaede.tagview.OnTagClickListener;
import me.kaede.tagview.Tag;
import me.kaede.tagview.TagView;

/**
 * Created by jeaman on 2017/6/22.
 * 直播开播view
 */

public class StartLiveNormalView extends StartLiveView implements TextView.OnEditorActionListener {
    private ImageView mCoverIv;
    private EditText mTitleEt;
    private View mChooseTagView;
    private EditText mCustomTagEt;
    private RecyclerView mRecyclerView;
    private TagView mTagView;
    private View mCoverTipIv;
    private View mCoverTipTv;

    private ChooseTagAdapter mAdapter;

    private OnNormalActionClickListener mListener;
    private boolean mAllowStartLive;    //是否允许开播

    public StartLiveNormalView(Context context) {
        super(context);
    }

    public StartLiveNormalView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public StartLiveNormalView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public StartLiveNormalView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        mCoverIv = (ImageView) findViewById(R.id.start_live_iv_cover);
        mTitleEt = (EditText) findViewById(R.id.start_live_et_title);
        mCoverTipIv = findViewById(R.id.start_live_iv_cover_tip);
        mCoverTipTv = findViewById(R.id.start_live_tv_cover_tip);

        TextView textView = (TextView) findViewById(R.id.start_live_tv_license);
        textView.setText(context.getString(R.string.push_license_tip));
        NoUnderlineClickableSpan urlSpan = new NoUnderlineClickableSpan(getResources().getColor(R.color.text_f0)) {
            @Override
            public void onClick(View widget) {
                if (mListener != null) {
                    mListener.onLicenseClick();
                }
            }
        };
        String license = context.getString(R.string.push_license);
        SpannableString spannableString = new SpannableString(license);
        spannableString.setSpan(urlSpan, 0, license.length(), Spanned.SPAN_MARK_MARK);
        textView.append(spannableString);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setLongClickable(false);
        textView.setHighlightColor(Color.TRANSPARENT);

        initChooseTagView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_start_live_normal;
    }

    @Override
    protected void initClickListener() {
        super.initClickListener();
        findViewById(R.id.start_live_iv_cover).setOnClickListener(this);
        findViewById(R.id.start_live_tv_tag).setOnClickListener(this);
        findViewById(R.id.start_live_ll_tag).setOnClickListener(this);
        findViewById(R.id.start_live_iv_share_weixin).setOnClickListener(this);
        findViewById(R.id.start_live_iv_share_friend).setOnClickListener(this);
        findViewById(R.id.start_live_iv_share_qq).setOnClickListener(this);
        findViewById(R.id.start_live_iv_share_weibo).setOnClickListener(this);
        findViewById(R.id.start_live_iv_share_qzone).setOnClickListener(this);
    }

    private void initChooseTagView() {
        mTagView = (TagView) findViewById(R.id.start_live_tag);
        mChooseTagView = findViewById(R.id.start_live_ll_tag);
        mCustomTagEt = (EditText) findViewById(R.id.start_live_et_tag_custom);
        mRecyclerView = (RecyclerView) findViewById(R.id.start_live_rv_tag_recycler);

        mAdapter = new ChooseTagAdapter(null);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext()).colorResId(R.color.divider_f0)
                .sizeResId(R.dimen.divider_size_choose_user)
                .build());
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                String tag = mAdapter.getItem(position);
                addTag(tag);

            }
        });
        mTagView.setOnTagClickListener(new OnTagClickListener() {
            @Override
            public void onTagClick(int position, Tag tag) {
                mTagView.remove(position);
                mAdapter.removeChooseTag(tag.text);
            }
        });

        mCustomTagEt.setOnEditorActionListener(this);
    }

    private boolean addTag(String tag) {
        try {
            if (mAdapter.toggleChooseTag(tag)) {
                mTagView.remove(tag);
                if (mTagView.getTags().size() == 0) {
                    mTagView.setVisibility(GONE);
                }
            } else {
                if (mTagView.getTags().size() == 0) {
                    mTagView.setVisibility(VISIBLE);
                }
                mTagView.addTag(new Tag(tag));
            }
            return true;
        } catch (Exception e) {
            ToastUtil.show(getContext(), R.string.tips_choose_tag_max);
        }
        return false;
    }

    public void setTagList(List<String> tagList) {
        mAdapter.setNewData(tagList);
    }

    public void showCoverTip() {
        mCoverTipIv.setVisibility(VISIBLE);
        mCoverTipTv.setVisibility(VISIBLE);
        //10秒自动隐藏
        postDelayed(new Runnable() {
            @Override
            public void run() {
                hideCoverTip();
            }
        }, 10000);
    }

    //隐藏开播封面气泡
    public void hideCoverTip() {
        mCoverTipIv.setVisibility(INVISIBLE);
        mCoverTipTv.setVisibility(INVISIBLE);
    }

    //开播信息请求回来才允许修改封面图和开始直播
    public void setStartEnabled(boolean enabled) {
        mAllowStartLive = enabled;
        mStartBtn.setEnabled(enabled);
    }

    public void setOnNormalActionClickListener(OnNormalActionClickListener listener) {
        super.setOnActionClickListener(listener);   //设置父类listener
        mListener = listener;
    }

    public void setCoverImage(Uri uri) {
        GlideUtil.loadImage(mCoverIv, uri, R.mipmap.btn_03fengmian);
    }

    public void setCoverImageUrl(String url) {
        GlideUtil.loadImage(mCoverIv, url, R.mipmap.btn_03fengmian);
    }

    public boolean onBackPressed() {
        if (mChooseTagView.getVisibility() == VISIBLE) {
            hideChooseTagView();
            return true;
        }
        return false;
    }

    private void showChooseTagView() {
        mTitleEt.setEnabled(false);
        mChooseTagView.setVisibility(VISIBLE);
        AnimationUtil.startFromBottomAnimation(mChooseTagView, 200, null);
    }

    private void hideChooseTagView() {
        mTitleEt.setEnabled(true);
        mChooseTagView.setVisibility(GONE);
        mCustomTagEt.clearFocus();
        KeyboardUtil.hideKeyboard(mCustomTagEt);
        AnimationUtil.startToBottomAnimation(mChooseTagView, 200, null);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.start_live_iv_cover:
                if (mAllowStartLive) {
                    mListener.onAddCoverClick();
                }
                break;
            case R.id.start_live_tv_tag:   //显示选择标签
                mListener.onAddTagClick();
                showChooseTagView();
                break;
            case R.id.start_live_ll_tag:   //关闭选择标签
                hideChooseTagView();
                break;
            case R.id.start_live_iv_share_weixin:
                mListener.onStartShareClick(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.start_live_iv_share_friend:
                mListener.onStartShareClick(SHARE_MEDIA.WEIXIN_CIRCLE);
                break;
            case R.id.start_live_iv_share_qq:
                mListener.onStartShareClick(SHARE_MEDIA.QQ);
                break;
            case R.id.start_live_iv_share_weibo:
                mListener.onStartShareClick(SHARE_MEDIA.SINA);
                break;
            case R.id.start_live_iv_share_qzone:
                mListener.onStartShareClick(SHARE_MEDIA.QZONE);
                break;
        }
    }

    public String getTitle() {
        return mTitleEt.getText().toString();
    }

    public List<String> getTagList() {
        List<String> tagList = null;
        if (mTagView.getTags().size() > 0) {
            tagList = new ArrayList<>();
            for (Tag tag : mTagView.getTags()) {
                tagList.add(tag.text);
            }
        }
        return tagList;
    }

    @Override
    public boolean onEditorAction(final TextView v, int actionId, KeyEvent event) {
        if (v == mCustomTagEt && actionId == v.getImeActionId()) {
            String tag = mCustomTagEt.getText().toString().trim();
            if (SensitiveWordFilterManager.getInstance().hasSensitiveWord(tag)) {
                ToastUtil.show(getContext(), R.string.live_sensitive_tag);
            } else {
                if (!TextUtils.isEmpty(tag) && addTag(tag)) {
                    mCustomTagEt.setText(null);
                }
            }
            mCustomTagEt.post(new Runnable() {
                @Override
                public void run() {
                    mCustomTagEt.requestFocus();
                }
            });
        }
        return false;
    }

    public interface OnNormalActionClickListener extends OnActionClickListener {
        void onLicenseClick();
        void onAddTagClick();
        void onAddCoverClick();
        void onStartShareClick(SHARE_MEDIA shareMedia);
    }

}
